import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { getCurrentDate,initLists } from '@/utils'

export const useCalendarStore = defineStore('calendar', () => {
  // 状态
  // 当前的日期
  const currentDate=getCurrentDate()
  // 选中的日期，使用当前日期作为初始值
  const selectedDate=ref(currentDate)
  
  // 计算属性:自动追踪响应式依赖，当依赖的源数据变化时，重新计算并更新
  // 数据只读
  // const year=computed(()=>selectedDate.value.year)
  // const month=computed(()=>selectedDate.value.month)
  // const date=computed(()=>selectedDate.value.date)
  // 使得下拉框数据可改可写
  const year=computed({
    get(){
      return selectedDate.value.year
    },
    set(value){
      selectedDate.value.year=value
    }
  })
  const month=computed({
    get(){
      return selectedDate.value.month
    },
    set(value){
      selectedDate.value.month=value
    }
  })
  const date=computed({
    get(){
      return selectedDate.value.date
    },
    set(value){
      selectedDate.value.date=value
    }
  })

  const lists=computed(()=>{
    return initLists(year.value,month.value)
  })

  const formatDate=computed(()=>{
    return `${year.value}-${month.value}-${date.value}`
  })

  const backToToday=()=>{
    selectedDate.value=getCurrentDate()
  }

  const prevMonth=()=>{
    // 计算本月天数
    const thisMonthDays=new Date(year.value,month.value,0).getDate()
    // 计算上个月天数
    const prevMonthDays=new Date(year.value,month.value-1,0).getDate()
    if(prevMonthDays<thisMonthDays){
      date.value=prevMonthDays
    }

    month.value=month.value-1
    if(month.value<1){
      year.value=year.value-1
      month.value=12
    } 
  }
  
  const nextMonth=()=>{
    // 计算本月天数
    const thisMonthDays=new Date(year.value,month.value,0).getDate()
    // 计算下个月天数
    const nextMonthDays=new Date(year.value,month.value+1,0).getDate()
    if(nextMonthDays<thisMonthDays){
      date.value=nextMonthDays
    }

    
    month.value=month.value+1
    if(month.value>12){
      year.value=year.value+1
      month.value=1
    }
  }

  return{
    year,
    month,
    date,
    backToToday,
    prevMonth,
    nextMonth,
    lists,
    formatDate
  }

})
